const Service = require('egg').Service;

class PowerService extends Service {


    // 查询权限
    async findPower(params = {}) {
        const pageSize = params && parseInt(params.pageSize) || 20; // 使用分页
        const page = params && parseInt(params.page) || 1;
        delete params.pageSize;
        delete params.page;
        return new Promise((resolve, reject) => {
            this.ctx.model.Power.find(params).limit(pageSize).skip(pageSize * (page - 1)).sort('-createDate').lean().exec((err, docs) => {
                if (err) {
                    console.log(err);
                    reject(err);
                } else {
                    resolve(docs);
                }
            })
        })
    }

    // 创建权限
    async createPower(data) {
        return new Promise(async (resolve, reject) => {
            this.ctx.model.Power({
                ...data
            }).save((err, data) => {
                if (err) {
                    console.log(err);
                    reject(err);
                    return
                }
                resolve(data)
            });
        })
    }

    // 查询单个权限
    async findOnePower(params = {}) {
        return new Promise((resolve, reject) => {
            this.ctx.model.Power.findOne(params).lean().exec((err, doc) => {
                if (err) {
                    console.log(err);
                    reject(err);
                } else {
                    resolve(doc);
                }
            });
        })
    }


    // 更新单个角色
    async updateOnePower(condition = {}, data) {
        return new Promise((resolve, reject) => {
            this.ctx.model.Power.updateOne(condition, data).lean().exec((err, doc) => {
                if (err) {
                    console.log(err);
                    reject(err);
                } else {
                    resolve(doc);
                }
            });
        })
    }
}

module.exports = PowerService;